package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.model.AreaInfo;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.common.util.RegexUtil;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;

public class AuthCompanyActivity extends BaseActivity implements
		OnClickListener {

	private EditText etCompanyName;
	private EditText etCompanyAddress;
	private EditText et_company_address_2;
	private EditText etContactor;
	private EditText etID;
	private EditText etPhone;
	private EditText etLicense;

	private ImageView btnLicence;
	private ImageView btnDoor;
	private ImageView btnID;
	private ImageView btnCard;

	private PictureInfo mBussInfo;// 营业执照
	private PictureInfo mDoorInfo;// 门头
	private PictureInfo mPIDInfo;// 身份证
	private PictureInfo mCardInfo;// 名片

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private int flag = 0;

	private String addressCode = "";

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESULT = 3;// 结果
	public static final int GET_AREA = 502;// 选择地址
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.COMPANY_AUTH_COMMIT_SUCCESSED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, "认证提交成功");
				finish();
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, (String) msg.obj);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		btnRight.setVisibility(View.VISIBLE);
		setContentView(R.layout.activity_auth_cargo);

		etCompanyName = (EditText) findViewById(R.id.et_company_name);
		etCompanyAddress = (EditText) findViewById(R.id.et_company_address);
		et_company_address_2 = (EditText) findViewById(R.id.et_company_address_2);
		etContactor = (EditText) findViewById(R.id.et_contactor);
		etID = (EditText) findViewById(R.id.et_id);
		etPhone = (EditText) findViewById(R.id.et_phone);
		etLicense = (EditText) findViewById(R.id.et_license);

		btnLicence = (ImageView) findViewById(R.id.btn_license);
		btnDoor = (ImageView) findViewById(R.id.btn_door);
		btnID = (ImageView) findViewById(R.id.btn_ID);
		btnCard = (ImageView) findViewById(R.id.btn_card);

		btnLicence.setOnClickListener(this);
		btnDoor.setOnClickListener(this);
		btnID.setOnClickListener(this);
		btnCard.setOnClickListener(this);

		etCompanyAddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent start = new Intent(mContext,
						ChoiceMainAreaActivity.class);
				start.putExtra("title", "选择公司地址");
				start.putExtra("is_mul", false);
				startActivityForResult(start, GET_AREA);
			}
		});

		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!check())
					return;

				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mBussInfo != null) {
					mPictures.add(mBussInfo);
				}
				if (mDoorInfo != null) {
					mPictures.add(mDoorInfo);
				}
				if (mPIDInfo != null) {
					mPictures.add(mPIDInfo);
				}
				if (mCardInfo != null) {
					mPictures.add(mCardInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				new UserRequest(mContext, mHandler).commitCompanyAuth(
						etCompanyName.getText().toString(), etCompanyAddress
								.getText().toString()
								+ et_company_address_2.getText().toString(),
						etLicense.getText().toString(), etContactor.getText()
								.toString(), etPhone.getText().toString(), etID
								.getText().toString(), addressCode, json);
			}
		});
	}

	@Override
	protected void onDestroy() {
		releaseImageView(btnCard);
		releaseImageView(btnDoor);
		releaseImageView(btnID);
		releaseImageView(btnLicence);
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PictureUtil.PHOTO_PICKED_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				// 设置裁剪尺寸
				intent.putExtra("aspectX", 1.5);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 375);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.CAMERA_WITH_DATA:
				data2 = PictureUtil.getCameraImageCaiUri();
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				intent.putExtra("aspectX", 1.5);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 375);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.PHOTO_CROP:
				Bundle bundle = data.getExtras();
				Bitmap myBitmap = (Bitmap) bundle.get("data");
				File file = Base64Util.saveBitmapToFile(myBitmap);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(myBitmap));
				myBitmap.recycle();
				info.setFilename(PictureUtil.getCharacterAndNumber() + ".png");
				if (flag == 0) {
					info.setType(PictureInfo.FileType.company);
					mBussInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnLicence);
				} else if (flag == 1) {
					info.setType(PictureInfo.FileType.door);
					mDoorInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnDoor);
				} else if (flag == 2) {
					info.setType(PictureInfo.FileType.citizen);
					mPIDInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnID);
				} else if (flag == 3) {
					info.setType(PictureInfo.FileType.card);
					mCardInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnCard);
				}
				break;
			default:
				break;
			}
		} else if (resultCode == GET_AREA) {
			if (data != null) {
				try {
					String addr = data.getStringExtra("addr");
					etCompanyAddress.setText(addr);
					addressCode = data.getStringExtra("areaCode");

					LLogger.e(addr + " " + addressCode);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1.5);
			intent.putExtra("aspectY", 1.0);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 600);
			intent.putExtra("outputY", 400);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_license:
			flag = 0;
			break;
		case R.id.btn_door:
			flag = 1;
			break;
		case R.id.btn_ID:
			flag = 2;
			break;
		case R.id.btn_card:
			flag = 3;
			break;
		default:
			break;
		}
		PictureUtil.doPickPhotoAction(mContext);
	}

	private boolean check() {
		// company name is needed
		if (StringUtil.isNull(etCompanyName.getText().toString().trim())) {
			etCompanyName.requestFocus();
			ToastHelper.toastShort(mContext, "请输入公司名称！");
			return false;
		}
		// company address is needed
		if (StringUtil.isNull(etCompanyAddress.getText().toString().trim())
				&& StringUtil.isNull(et_company_address_2.getText().toString()
						.trim())) {
			et_company_address_2.requestFocus();
			ToastHelper.toastShort(mContext, "请输入公司地址！");
			return false;
		}

		if (StringUtil.isNull(etLicense.getText().toString().trim())) {
			etLicense.requestFocus();
			ToastHelper.toastShort(mContext, "请输入工商执照号码！");
			return false;
		}

		if (!RegexUtil.CheckIDNum(etID.getText().toString().trim())) {
			etID.requestFocus();
			ToastHelper.toastShort(mContext, "请输入正确的身份证号码！");
			return false;
		}

		return true;
	}
}
